import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_qiniu/flutter_qiniu.dart';
import 'package:image_picker/image_picker.dart';
import 'package:logger/logger.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:qgchat/common/class/upload/upload.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:qgchat/widgets/iosBottomSheet.dart';
import 'package:qgchat/widgets/loading.dart';

/*
 * 发布视频页面
 */

class Uploadvideo extends StatefulWidget {
  Uploadvideo({Key key}) : super(key: key);

  @override
  _UploadvideoState createState() => _UploadvideoState();
}

class _UploadvideoState extends State<Uploadvideo> {
  bool ispay = false; //是否付费观看

  String selectgold = ''; //选择的金币

  String uploadpath = ''; //上传视频的路径

  String copywriting = ''; //填写的文案

  String videoUrl = ''; // 视频地址

  String videosize = ''; // 视频大小

  String thumbnail = ''; // 视频缩略图

  int minUploadTime = 1000 * 5; // 最小上传时间(ms)
  int maxUploadTime = 1000 * 60; // 最大上传时间(ms)

  // 实例化七牛云
  final qiniu = FlutterQiniu(zone: QNFixedZone.zone2);

  bool isShowLoad = false;
  String text = '';

// hook-------------------------------------------------------------------------

  @override
  void reassemble() {
    super.reassemble();
  }

// methods----------------------------------------------------------------------

  // 渲染范围内的递增数组
  List<String> increaseListRender(min, max) {
    List<String> arr = [];
    for (var i = 0; i <= (max - min); i++) {
      String item = (min + i).toString();
      arr.add(item);
    }
    return arr;
  }

  // 显示底部面板
  showBottomSheet() {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext ctx) {
        return CupertinoActionSheet(
          title: Text("选择视频"),
          message: Text("选择以下选项获取视频"),
          cancelButton: CupertinoActionSheetAction(
            onPressed: () => Navigator.pop(ctx),
            child: Text("取消"),
          ),
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () async {
                try {
                  Navigator.pop(ctx);
                  final file = await ImagePicker.pickVideo(source: ImageSource.camera);
                  final url = await Upload.qiniuUploadVideo(context, file);
                  videoUrl = url;
                  thumbnail = "$url?vframe/jpg/offset/0";
                  setState(() {});
                } catch (e) {
                  if (e is String) toast(e);
                }
              },
              child: Text("相机"),
            ),
            CupertinoActionSheetAction(
              onPressed: () async {
                try {
                  Navigator.pop(ctx);
                  final file = await ImagePicker.pickVideo(source: ImageSource.gallery);
                  final url = await Upload.qiniuUploadVideo(context, file);
                  videoUrl = url;
                  thumbnail = "$url?vframe/jpg/offset/0";
                  setState(() {});
                } catch (e) {
                  if (e is String) toast(e);
                }
              },
              child: Text("系统相册"),
            ),
          ],
        );
      },
    );
  }

  // 上传文件
  uploadVideo(File video) async {
    if (video == null) return;

    setState(() {
      isShowLoad = true;
      text = '上传中，请稍等';
    });

    // 实例化压缩类
    // CompressVideo compressVideo = CompressVideo(video);

    // 获取视频信息
    // MediaInfo videoInfo = await compressVideo.getVideoInfo();
    // proportion = videoInfo.width / videoInfo.height;

    // 压缩视频
    // MediaInfo renderVideo = await VideoCompress.compressVideo(
    //   video.path,
    //   quality: VideoQuality.LowQuality,
    //   deleteOrigin: false, // It's false by default
    // );
    // String name = renderVideo.path.substring(
    //   renderVideo.path.lastIndexOf('/') + 1,
    //   renderVideo.path.length,
    // );
    // todo 升级dio3
    // FormData formData = FormData.from({
    //   'file': UploadFileInfo(
    //     renderVideo.file,
    //     name,
    //   ),
    // });
    // FormData formData = FormData.fromMap({
    //   "file":
    //       await MultipartFile.fromFile(renderVideo.file.path, filename: name)
    // });

    // // 上传
    // var res = await Io.post('vedio/upload1', data: formData, debug: true);
    // Logger().i(res);
    // if (res['status'] == 1) {
    //   // 七牛云上传
    //   String resultKey = await qiniu.uploadFile(
    //     renderVideo.file.path,
    //     'x55i6njUrpfQp7oF4C7q8KGUOKChwsP4Ii3gZWMJ',
    //     res['data']['token'],
    //   );

    //   if (resultKey == '') {
    //     showToast('上传视频过短,请重新上传');
    //     setState(() {
    //       isShowLoad = false;
    //       text = '';
    //     });
    //     return;
    //   }
    //   setState(() {
    //     thumbnail = res['data']['domain'] + resultKey + '?vframe/jpg/offset/1';
    //     videoUrl = res['data']['domain'] + resultKey;
    //     // videosize = res['data']['videosize'];
    //     isShowLoad = false;
    //     text = '';
    //   });
    //   showToast('上传成功');
    // } else {
    //   setState(() {
    //     isShowLoad = false;
    //     text = '';
    //   });
    //   showToast(res['msg']);
    // }
  }

  // 是否删除视频对话框
  judgedelectvideo() {
    showDialog(
      context: context,
      child: CupertinoAlertDialog(
        title: Text('是否删除此视频'),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text('是'),
            onPressed: () {
              setState(() {
                videoUrl = ''; // 视频地址
                videosize = ''; // 视频大小
                thumbnail = ''; // 视频缩略图
              });
              Navigator.of(context).pop();
            },
          ),
          CupertinoDialogAction(
            child: Text('否'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }

// widget-----------------------------------------------------------------------

  // 等待框
  Widget waitdiglog(BuildContext context, tips) {
    return new Material(
      type: MaterialType.transparency,
      child: new Center(
        child: new Container(
          decoration: new ShapeDecoration(
            color: Colors.white,
            shape: new RoundedRectangleBorder(
              borderRadius: new BorderRadius.all(
                new Radius.circular(10),
              ),
            ),
          ),
          width: 200,
          height: 100,
          padding: EdgeInsets.all(10),
          child: new Column(
            children: <Widget>[
              CircularProgressIndicator(),
              new Text(
                tips,
                style: TextStyle(fontSize: 12, color: Colors.grey),
                softWrap: false,
              )
            ],
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          ),
        ),
      ),
    );
  }

  /// appbar
  Widget appbar() {
    UserState userState = (state(context, 'user') as UserState);
    return AppBar(
      title: Text(
        '上传视频',
        style: TextStyle(fontSize: px(34), fontWeight: FontWeight.bold),
      ),
      centerTitle: true,
      actions: <Widget>[
        GestureDetector(
          onTapUp: (val) {
            if (videoUrl == '' && videoUrl == null) {
              return showToast('视频上传中，请稍后...');
            }
            UserApis.uploadcopying(
              copywriting,
              videoUrl,
              ispay ? 1 : 0,
              selectgold,
              videosize,
              userState.info.memberToken,
              thumbnail,
            ).then((res) {
              if (res['status'] == 1) {
                showToast('发布成功');
                Navigator.of(context).pop();
              } else {
                showToast(res['msg']);
              }
            });
          },
          child: Container(
            margin: EdgeInsets.only(
              top: px(40),
              right: px(30),
            ),
            child: Text(
              '发布',
              style: TextStyle(
                color: col('5640c6'),
                fontSize: px(34),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appbar(),
      backgroundColor: col('f5f7fa'),
      body: Container(
          child: Stack(
        children: <Widget>[
          ListView(
            children: <Widget>[
              TextField(
                maxLines: 10,
                onChanged: (v) {
                  setState(() {
                    copywriting = v;
                  });
                },
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.only(
                    left: px(31),
                    top: px(19),
                  ),
                  hintText: '记录此刻的心情吧',
                  fillColor: Colors.white,
                  filled: true,
                  border: UnderlineInputBorder(
                    borderSide: BorderSide(
                      color: col('edeff2'),
                      width: px(1),
                    ),
                  ),
                  hintStyle: TextStyle(
                    fontSize: px(34),
                    color: col('bfc2cc'),
                  ),
                ),
              ),
              Container(
                color: Colors.white,
                child: videoUrl == ''
                    ? GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTapUp: (val) => showBottomSheet(),
                        child: Container(
                          margin: EdgeInsets.all(px(30)),
                          width: px(116),
                          height: px(116),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(
                              width: px(1),
                              color: col('edeff2'),
                            ),
                          ),
                          child: Container(
                            width: px(56),
                            height: px(56),
                            child: Icon(
                              Icons.add,
                              color: col('bfc2cc'),
                            ),
                          ),
                        ),
                      )
                    : GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onLongPress: () => judgedelectvideo(),
                        child: Container(
                          margin: EdgeInsets.all(px(30)),
                          height: px(400),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(
                              width: px(1),
                              color: col('edeff2'),
                            ),
                          ),
                          child: Image.network(
                            "$videoUrl?vframe/jpg/offset/0",
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
              ),
              Container(
                margin: EdgeInsets.only(
                  top: px(16),
                ),
                padding: EdgeInsets.only(
                  left: px(30),
                ),
                color: Colors.white,
                child: Column(
                  children: <Widget>[
                    Container(
                      width: px(720),
                      height: px(88),
                      decoration: BoxDecoration(
                        border: Border(
                          bottom:
                              BorderSide(width: px(1), color: col('edeff2')),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Text('付费观看'),
                          CupertinoSwitch(
                            value: ispay,
                            activeColor: col('6f53ff'),
                            onChanged: (bool value) {
                              ///点击切换开关的状态
                              setState(() {
                                ispay = !ispay;
                              });
                            },
                          )
                        ],
                      ),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTapUp: (val) {
                        showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.white,
                          isScrollControlled: true,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(px(28)),
                              topRight: Radius.circular(px(28)),
                            ),
                          ),
                          builder: (BuildContext context) {
                            return IosBottomSheet(increaseListRender(1, 50),
                                (item, index) {
                              setState(() {
                                selectgold = item;
                              });
                            });
                          },
                        );
                      },
                      child: Container(
                        width: px(720),
                        height: px(88),
                        padding: EdgeInsets.only(
                          right: px(30),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text('请设置金币数量'),
                            Container(
                              child: Row(
                                children: <Widget>[
                                  Offstage(
                                    offstage: selectgold != '' ? false : true,
                                    child: Container(
                                      margin: EdgeInsets.only(
                                        right: px(40),
                                      ),
                                      child: Text('$selectgold金币'),
                                    ),
                                  ),
                                  Image.asset(
                                    'assets/images/icon/right.png',
                                    width: px(14),
                                    height: px(26),
                                  )
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
          Loading(
            isShowLoad,
            text: text,
          ),
        ],
      )),
    );
  }
}
